<?php
session_start();
// 数据库配置
define('DB_HOST', '127.0.0.1');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', '123456');
define('TABLE_NAME', 'iot_dev_copy1');

// 系统密码
define('SYSTEM_PASSWORD', '6226767');

// 分页设置
$per_page = 15; // 每页显示记录数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max($page, 1); // 确保页码不小于1
$offset = ($page - 1) * $per_page;

// 处理退出请求
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// 连接数据库
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("数据库连接失败: " . $conn->connect_error);
}

// 处理登录
if (isset($_POST['login'])) {
    $password = $_POST['password'] ?? '';
    if ($password === SYSTEM_PASSWORD) {
        $_SESSION['logged_in'] = true;
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    } else {
        $login_error = "密码错误，请重试";
    }
}

// 处理搜索请求
$search_term = '';
if (isset($_GET['search']) && !empty(trim($_GET['search']))) {
    $search_term = $conn->real_escape_string(trim($_GET['search']));
    $search_sql = "SELECT id, idcode, name, is_online FROM ".TABLE_NAME." 
                  WHERE idcode LIKE '%$search_term%' OR name LIKE '%$search_term%'
                  ORDER BY id DESC LIMIT $offset, $per_page";
    
    $count_sql = "SELECT COUNT(*) as total FROM ".TABLE_NAME." 
                 WHERE idcode LIKE '%$search_term%' OR name LIKE '%$search_term%'";
} else {
    $search_sql = "SELECT id, idcode, name, is_online FROM ".TABLE_NAME." 
                  ORDER BY id DESC LIMIT $offset, $per_page";
    $count_sql = "SELECT COUNT(*) as total FROM ".TABLE_NAME;
}

// 执行查询
$result = $conn->query($search_sql);
$devices = [];
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
}

// 获取总记录数
$total_records = 0;
$count_result = $conn->query($count_sql);
if ($count_result) {
    $total_records = $count_result->fetch_assoc()['total'];
}
$total_pages = ceil($total_records / $per_page);   



// 获取设备详情
if (isset($_GET['action']) && $_GET['action'] == 'detail' && isset($_GET['id'])) {
    $deviceId = (int)$_GET['id'];
    $sql = "SELECT name, idcode, camera_serial, camera_code, speed, vision, runtime, remark 
            FROM ".TABLE_NAME." 
            WHERE id = $deviceId";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $deviceDetail = $result->fetch_assoc();
        // 检查二级密码状态
        $isSecondaryActive = ($deviceDetail['speed'] == 7 && 
                             $deviceDetail['vision'] == 7 && 
                             $deviceDetail['runtime'] == 7);
    } else {
        $detail_error = "设备不存在";
    }
}

// 获取设备数据（最新10条）
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($current_page - 1) * $per_page;

$sql = "SELECT id, idcode, name, is_online FROM ".TABLE_NAME." ORDER BY id DESC LIMIT $offset, $per_page";
$result = $conn->query($sql);
$devices = [];
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
}

// 获取总记录数
$count_result = $conn->query("SELECT COUNT(*) as total FROM ".TABLE_NAME);
$total_records = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $per_page);

// 关闭连接
$conn->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物联网设备管理系统</title>
    
    <!-- 引入Ant Design样式 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/antd/4.21.7/antd.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #1890ff;
            --success-color: #52c41a;
            --error-color: #f5222d;
            --warning-color: #faad14;
            --text-color: #333;
            --border-color: #d9d9d9;
            --background-light: #f5f5f5;
            --card-shadow: 0 3px 6px -4px rgba(0,0,0,0.12), 0 6px 16px 0 rgba(0,0,0,0.08), 0 9px 28px 8px rgba(0,0,0,0.05);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f0f2f5;
            color: var(--text-color);
            line-height: 1.5;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        /* 头部样式 */
        header {
            background: linear-gradient(135deg, #1890ff 0%, #0050b3 100%);
            color: white;
            padding: 15px 0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            display: flex;
            align-items: center;
            font-size: 20px;
            font-weight: bold;
        }
        
        .logo i {
            margin-right: 10px;
            font-size: 24px;
        }
        
        /* 主内容区 */
        .main-content {
            padding: 24px 0;
            min-height: calc(100vh - 150px);
        }
        
        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: var(--card-shadow);
            margin-bottom: 24px;
            overflow: hidden;
        }
        
        .card-header {
            padding: 16px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .card-title {
            font-size: 18px;
            font-weight: 500;
            margin: 0;
        }
        
        .card-body {
            padding: 24px;
        }
        
        /* 表格样式 */
        .table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
        }
        
        .table th {
            background-color: #fafafa;
            text-align: left;
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
            font-weight: 500;
        }
        
        .table td {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }
        
        .table tr:hover td {
            background-color: #fafafa;
        }
        
        /* 按钮样式 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 6px 16px;
            border-radius: 4px;
            border: 1px solid transparent;
            font-size: 14px;
            font-weight: 400;
            cursor: pointer;
            transition: all 0.3s;
            height: 32px;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #40a9ff;
            border-color: #40a9ff;
        }
        
        .btn-default {
            background-color: white;
            color: var(--text-color);
            border-color: var(--border-color);
        }
        
        .btn-default:hover {
            background-color: #fafafa;
            border-color: #40a9ff;
            color: #40a9ff;
        }
        
        .btn-sm {
            padding: 0 8px;
            height: 24px;
            font-size: 12px;
        }
        
        /* 状态标签 */
        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .status-online {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        
        .status-offline {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        
        /* 模态框 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        
        .modal-content {
            background-color: white;
            border-radius: 4px;
            width: 600px;
            max-width: 90%;
            box-shadow: 0 6px 16px 0 rgba(0,0,0,0.08), 0 3px 6px -4px rgba(0,0,0,0.12), 0 9px 28px 8px rgba(0,0,0,0.05);
        }
        
        .modal-header {
            padding: 16px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 16px;
            font-weight: 500;
            margin: 0;
        }
        
        .modal-body {
            padding: 24px;
            max-height: 70vh;
            overflow-y: auto;
        }
        
        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--border-color);
            text-align: right;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: rgba(0,0,0,0.45);
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            height: 32px;
            transition: border 0.3s;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
        }
        
        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 24px;
            list-style: none;
        }
        
        .pagination li {
            margin: 0 4px;
        }
        
        .pagination a {
            display: block;
            min-width: 32px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            text-decoration: none;
            color: var(--text-color);
        }
        
        .pagination a:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }
        
        .pagination .active a {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }
        
        .pagination .disabled a {
            color: rgba(0,0,0,0.25);
            cursor: not-allowed;
        }
        
        /* 登录页样式 */
        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background: linear-gradient(135deg, #1890ff 0%, #0050b3 100%);
        }
        
        .login-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 8px 20px rgba(0,0,0,0.15);
            width: 400px;
            padding: 40px;
        }
        
        .login-title {
            text-align: center;
            margin-bottom: 30px;
            color: var(--text-color);
            font-size: 24px;
        }
        
        .error-message {
            color: var(--error-color);
            margin-top: 10px;
            text-align: center;
        }
        
        .success-message {
            color: var(--success-color);
            margin-top: 10px;
            text-align: center;
        }
        
        /* 二级密码状态 */
        .password-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
        }
        
        .status-active {
            background-color: #f6ffed;
            color: var(--success-color);
            border: 1px solid #b7eb8f;
        }
        
        .status-inactive {
            background-color: #fff2f0;
            color: var(--error-color);
            border: 1px solid #ffccc7;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .table-responsive {
                overflow-x: auto;
            }
            
            .table th, .table td {
                padding: 12px 8px;
            }
            
            .login-card {
                width: 90%;
                padding: 30px 20px;
            }
        }
        /*.header-actions {*/
        /*        display: flex;*/
        /*        align-items: center;*/
        /*        justify-content: flex-end;*/
        /*        flex-grow: 1;*/
        /*    }*/
        /*    .search-form {*/
        /*        width: 300px;*/
        /*    }*/
        /*    .input-group {*/
        /*        width: auto;*/
        /*    }*/
        
        
    </style>
</head>
<body>
    <?php if (!isset($_SESSION['logged_in'])): ?>
        <!-- 登录页面 -->
        <div class="login-container">
            <div class="login-card">
                <h1 class="login-title">物联网设备添加管理系统</h1>
                <form method="post">
                    <div class="form-group">
                        <label class="form-label" for="password">密码访问</label>
                        <input type="password" class="form-control" id="password" name="password" required autocomplete="off">
                    </div>
                    <button type="submit" name="login" class="btn btn-primary" style="width: 100%; margin-top: 10px;">登录系统</button>
                    <?php if (isset($login_error)): ?>
                        <div class="error-message"><?php echo $login_error; ?></div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    <?php else: ?>
        <!-- 主页面 -->
        <header>
            <div class="container">
                <div class="header-content">
                    <div class="logo">
                        <i class="fas fa-microchip"></i>
                        <span>物联网设备管理系统</span>
                    </div>
                    <div class="user-info">
                        <span style="margin-right: 15px;">管理员</span>
                        <a href="?logout" class="btn btn-default btn-sm">退出</a>
                    </div>
                </div>
            </div>
        </header>
        
        <div class="container">
            <div class="main-content">
            <!-- 设备列表卡片 -->
            <div class="card">
                <div class="card-header">
                    <h2 class="card-title">设备列表</h2>
                    <div class="header-actions">
                        <form method="get" class="search-form" style="display: inline-block; margin-right: 10px;">
                            <div class="input-group">
                                <input type="text" name="search" class="form-control" placeholder="搜索设备ID或名称" 
                                       value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="submit">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </form>
                        <button class="btn btn-primary" onclick="openAddModal()">
                            <i class="fas fa-plus"></i> 添加设备
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (isset($add_success)): ?>
                        <div class="success-message"><?php echo $add_success; ?></div>
                    <?php endif; ?>
                    
                    <?php if (isset($add_error)): ?>
                        <div class="error-message"><?php echo $add_error; ?></div>
                    <?php endif; ?>

                        
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>设备名称</th>
                                        <th>设备ID</th>
                                        <th>在线状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (count($devices) > 0): ?>
                                        <?php $counter = ($current_page - 1) * $per_page + 1; ?>
                                        <?php foreach ($devices as $device): ?>
                                            <tr>
                                                <td><?php echo $counter++; ?></td>
                                                <td><?php echo htmlspecialchars($device['name']); ?></td>
                                                <td><?php echo htmlspecialchars($device['idcode']); ?></td>
                                                <td>
                                                    <span class="status-tag <?php echo $device['is_online'] ? 'status-online' : 'status-offline'; ?>">
                                                        <?php echo $device['is_online'] ? '在线' : '离线'; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <a href="?action=detail&id=<?php echo $device['id']; ?>" class="btn btn-default btn-sm">
                                                        <i class="fas fa-info-circle"></i> 详情
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="5" style="text-align: center;">暂无设备数据</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页 -->
                        <?php if ($total_pages > 1): ?>
                            <ul class="pagination">
                                <li class="<?php echo $current_page <= 1 ? 'disabled' : ''; ?>">
                                    <a href="?page=1">首页</a>
                                </li>
                                <li class="<?php echo $current_page <= 1 ? 'disabled' : ''; ?>">
                                    <a href="?page=<?php echo max(1, $current_page - 1); ?>">上一页</a>
                                </li>
                                
                                <?php
                                // 显示前后5页
                                $start_page = max(1, $current_page - 5);
                                $end_page = min($total_pages, $current_page + 5);
                                
                                for ($i = $start_page; $i <= $end_page; $i++): ?>
                                    <li class="<?php echo $current_page == $i ? 'active' : ''; ?>">
                                        <a href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="<?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a href="?page=<?php echo min($total_pages, $current_page + 1); ?>">下一页</a>
                                </li>
                                <li class="<?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>">
                                    <a href="?page=<?php echo $total_pages; ?>">末页</a>
                                </li>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 添加设备模态框 -->
        <div id="addModal" class="modal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">添加物联网设备</h3>
                    <button class="close-btn" onclick="closeAddModal()">&times;</button>
                </div>
                <form method="post">
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="form-label" for="idcode">设备ID *</label>
                            <input type="text" class="form-control" id="idcode" name="idcode" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="name">设备名称 *</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="remark">门禁主板ID</label>
                            <input type="text" class="form-control" id="remark" name="remark">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" onclick="closeAddModal()">取消</button>
                        <button type="submit" name="add_device" class="btn btn-primary">确认添加</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 设备详情模态框 -->
        <?php if (isset($_GET['action']) && $_GET['action'] == 'detail'): ?>
            <div id="detailModal" class="modal" style="display:flex;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">设备详情</h3>
                        <button class="close-btn" onclick="closeDetailModal()">&times;</button>
                    </div>
                    <div class="modal-body" id="detailContent">
                        <?php if (isset($detail_error)): ?>
                            <div class="error-message"><?php echo $detail_error; ?></div>
                        <?php else: ?>
                            <div class="form-group">
                                <label class="form-label">设备名称</label>
                                <div class="form-control"><?php echo htmlspecialchars($deviceDetail['name']); ?></div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">设备ID</label>
                                <div class="form-control"><?php echo htmlspecialchars($deviceDetail['idcode']); ?></div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">摄像头序列号</label>
                                    <div class="form-control">
                                        <?php if (!empty($deviceDetail['camera_serial'])): ?>
                                            <?php echo htmlspecialchars($deviceDetail['camera_serial']); ?>
                                        <?php else: ?>
                                            <span class="text-muted">未设置</span>
                                        <?php endif; ?>
                                    </div>
                            </div>
                            <div class="form-group">
                                <label class="form-label">摄像头密码</label>
                                <!--<div class="form-control"><?php echo htmlspecialchars($deviceDetail['camera_code']); ?></div>-->
                                <div class="form-control">
                                    <?php if (!empty($deviceDetail['camera_code'])): ?>
                                        <?php echo htmlspecialchars($deviceDetail['camera_code']); ?>
                                    <?php else: ?>
                                        <span class="text-muted">未设置</span>
                                    <?php endif; ?>
                                </div>

                            </div>
                            <div class="form-group">
                                <label class="form-label">二级密码状态</label>
                                <div class="password-status <?php echo $isSecondaryActive ? 'status-inactive' : 'status-active'; ?>">
                                    <?php echo $isSecondaryActive ? '已取消' : '已启用'; ?>
                                </div>
                                <p style="margin-top:8px;font-size:12px;color:#999;">
                                    <?php if ($isSecondaryActive): ?>
                                        <i class="fas fa-exclamation-circle"></i> 二级密码已取消（状态值均为7）
                                    <?php else: ?>
                                        <i class="fas fa-check-circle"></i> 二级密码已启用
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div class="form-group">
                                <label class="form-label">门禁主板ID</label>
                                <!--<div class="form-control"><?php echo htmlspecialchars($deviceDetail['remark']); ?></div>-->
                                <div class="form-control">
                                        <?php if (!empty($deviceDetail['remark'])): ?>
                                            <?php echo htmlspecialchars($deviceDetail['remark']); ?>
                                        <?php else: ?>
                                            <span class="text-muted">未设置</span>
                                        <?php endif; ?>
                                    </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" onclick="closeDetailModal()">关闭</button>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <script>
            // 模态框控制函数
            function openAddModal() {
                document.getElementById('addModal').style.display = 'flex';
            }
            
            function closeAddModal() {
                document.getElementById('addModal').style.display = 'none';
            }
            
            function openDetailModal() {
                document.getElementById('detailModal').style.display = 'flex';
            }
            
            function closeDetailModal() {
                window.location.href = '<?php echo strtok($_SERVER["REQUEST_URI"], '?'); ?>';
            }
            
            // 关闭模态框当点击外部
            window.onclick = function(event) {
                const modals = document.getElementsByClassName('modal');
                for (let modal of modals) {
                    if (event.target === modal) {
                        modal.style.display = "none";
                    }
                }
            }
        </script>
    <?php endif; ?>
    
    <?php
    // 处理退出
    if (isset($_GET['logout'])) {
        unset($_SESSION['logged_in']);
        session_destroy();
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
    ?>
</body>
</html>